package com.xs.ahoi.hcxs.wxapi;

import android.os.Bundle;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.ui.activity.BaseActivity;
import com.xs.ahoi.hcxs.utils.ToastUtil;

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    private final String APPID = "wxd8943fd468114944";
    private IWXAPI wx_api; //全局的微信api对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxentry);

        wx_api = WXAPIFactory.createWXAPI(this, APPID, true);
        wx_api.registerApp(APPID);

        // 该句必须写,不然没有回调
        wx_api.handleIntent(getIntent(), this);

        login();
    }

    // 防止重复登录
    public void login() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        wx_api.sendReq(req);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {

            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                ToastUtil.show("授权出错");
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                ToastUtil.show("取消登录");
                break;
            case BaseResp.ErrCode.ERR_OK:
                ToastUtil.show("授权成功,正在登录");
                String code = ((SendAuth.Resp) resp).code;

                //通过该code值获取access_token
                //调用接口https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
//然后根据返回的access_token和code值调用如下接口获取用户信息
//https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN


                break;
        }
    }
}
